﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BasePlatformNet;
using System.IO;
using Newtonsoft.Json;
using BasePlatformCommon.devChain;
using BasePlatformCommon;

namespace L9SubSet
{
	public partial class Form_SelectSubEx : Form
	{
		private SelectedSubInfo selectedSubInfo = null;		// 分控选择参数

		private string mode = "";

		private Form_MainSet parent_parent = null;

		private BaseCoreNet baseCoreNet = null;

		private int totalSubCtrlNum = 0;
		private int totalSubCtrlNumInLwf = 0;

		// 当前处于编辑状态的控件
		private bool editFormatAction = true;
		private DataGridViewTextBoxEditingControl editingControl;
		private string lastEffectEditString = "";

		// 初始化完成标记
		private bool initDone = false;

		private string section = "SelectSubEx";				// 多语言文件配置节名称

		private string tip = "提示";							// MessageBox 题头

		/*****************************************************************************************/

		// 构造函数
		public Form_SelectSubEx(Form_MainSet parent_parent, SelectedSubInfo selectedSubInfo, BaseCoreNet baseCoreNet)
		{
			InitializeComponent();

			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
			this.Font = new System.Drawing.Font(this.Font.Name, 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel, ((byte)(134)));

			this.parent_parent = parent_parent;
			this.selectedSubInfo = selectedSubInfo;
			this.baseCoreNet = baseCoreNet;

			List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
			totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;
			string text = string.Format("布线文件中的所有分控（{0}个）", totalSubCtrlNum);
			if (LanguageOper.available == true)
			{
				text = string.Format(LanguageOper.ReadValue(section, "allRadioButton.Text"), totalSubCtrlNum);
			}
			allRadioButton.Text = text;

			initEnvironment();
		}

		// 构造函数
		public Form_SelectSubEx(Form_MainSet parent_parent, SelectedSubInfo selectedSubInfo, BaseCoreNet baseCoreNet, string mode)
		{
			InitializeComponent();

			this.parent_parent = parent_parent;
			this.selectedSubInfo = selectedSubInfo;
			this.baseCoreNet = baseCoreNet;
			this.mode = mode;

			if (mode.Equals("DownloadAddrMap"))
			{
				totalSubCtrlNumInLwf = baseCoreNet.getSubControlNumInLwf();
				string text = string.Format("所有分控（以布线文件为准, {0}个）", totalSubCtrlNumInLwf);
				if (LanguageOper.available == true)
				{
					text = string.Format(LanguageOper.ReadValue(section, "msgStr.1"), totalSubCtrlNumInLwf);
				}
				allRadioButton.Text = text;
			}
			else
			{
				List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
				totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;
				string text = string.Format("所有分控（以检测为准, {0}个）", totalSubCtrlNum);
				if (LanguageOper.available == true)
				{
					text = string.Format(LanguageOper.ReadValue(section, "msgStr.0"), totalSubCtrlNum);
				}
				allRadioButton.Text = text;
			}

			initEnvironment();
		}

		// 初始化运行环境
		private void initEnvironment()
		{
			configGroupBox.Enabled = false;

			// 初始化菜单项
			AddContextMenu("新建", configContextMenuStrip.Items, newLwfConfigFile_Click);
			AddContextMenu("打开", configContextMenuStrip.Items, openLwfConfigFile_Click);
			AddContextMenu("保存", configContextMenuStrip.Items, saveLwfConfigFile_Click);

			manualOffsetTextBox.Text = "1";

			// 设置本地化语言
			if (LanguageOper.available == true)
			{
				setLanguageText();
			}

			initDone = true;
		}

		// 设置本地化语言
		public void setLanguageText()
		{
			if (LanguageOper.available == false)
			{
				return;
			}

			LanguageOper.SetCurrentCulture();

			tip = LanguageOper.ReadValue("Common", "tipStr");

			// 显示菜单项
			configContextMenuStrip.Items[0].Text = LanguageOper.ReadValue(section, "configItem.Text.0");
			configContextMenuStrip.Items[1].Text = LanguageOper.ReadValue(section, "configItem.Text.1");
			configContextMenuStrip.Items[2].Text = LanguageOper.ReadValue(section, "configItem.Text.2");

			// 布线配置表列头
			configDataGridView.Columns[0].HeaderText = LanguageOper.ReadValue(section, "configHead.Text.0");
			configDataGridView.Columns[1].HeaderText = LanguageOper.ReadValue(section, "configHead.Text.1");
			configDataGridView.Columns[2].HeaderText = LanguageOper.ReadValue(section, "configHead.Text.2");
			configDataGridView.Columns[3].HeaderText = LanguageOper.ReadValue(section, "configHead.Text.3");
			configDataGridView.Columns[4].HeaderText = LanguageOper.ReadValue(section, "configHead.Text.4");

			// 界面控件文字
			this.Text = LanguageOper.ReadValue(section, "selectSubEx.Text");
			manualOffsetCheckBox.Text = LanguageOper.ReadValue(section, "manualOffsetCheckBox.Text");
			indexRadioButton.Text = LanguageOper.ReadValue(section, "indexRadioButton.Text");
			indexMiddleLabel.Text = LanguageOper.ReadValue(section, "indexMiddleLabel.Text");
			useTableCheckBox.Text = LanguageOper.ReadValue(section, "useTableCheckBox.Text");
			configGroupBox.Text = LanguageOper.ReadValue(section, "configGroupBox.Text");
			configButton.Text = LanguageOper.ReadValue(section, "configButton.Text");
			preTreatCheckBox.Text = LanguageOper.ReadValue(section, "preTreatCheckBox.Text");
			
			List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
			totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;
			string text = string.Format("布线文件中的所有分控（{0}个）", totalSubCtrlNumInLwf);
			if (LanguageOper.available == true)
			{
				text = string.Format(LanguageOper.ReadValue(section, "allRadioButton.Text"), totalSubCtrlNumInLwf);
			}
			allRadioButton.Text = text;
			
			okButton.Text = LanguageOper.ReadValue(section, "okButton.Text");
			cancelButton.Text = LanguageOper.ReadValue(section, "cancelButton.Text");
			if (LanguageOper.LocalLanguage != LanguageEnum.EN)
			{
				manualOffsetCheckBox.Location = new Point(303, 16);
				manualOffsetTextBox.Location = new Point(413, 14);
				useTableCheckBox.Location = new Point(303, 44);
				indexMiddleLabel.Location = new Point(181, 43);
			}
			else
			{
				manualOffsetCheckBox.Location = new Point(303, 16);
				manualOffsetTextBox.Location = new Point(448, 14);
				useTableCheckBox.Location = new Point(303, 44);
				indexMiddleLabel.Location = new Point(181, 43);
			}
		}

		// 指定分控
		private void specRadioButton_CheckedChanged(object sender, EventArgs e)
		{
			indexMiddleLabel.Enabled = indexRadioButton.Checked;
			indexStartTextBox.Enabled = indexRadioButton.Checked;
			indexEndTextBox.Enabled = indexRadioButton.Checked;
			manualOffsetCheckBox.Enabled = indexRadioButton.Checked;
			if (indexRadioButton.Checked == false)
			{
				manualOffsetTextBox.Enabled = false;
			}
			else
			{
				manualOffsetTextBox.Enabled = manualOffsetCheckBox.Checked;
			}
		}

		// 确定
		private void okButton_Click(object sender, EventArgs e)
		{
			selectedSubInfo.sourceSubIndexList.Clear();
			selectedSubInfo.targetSubIndexList.Clear();

			List<ControlNode> controlNodeList = baseCoreNet.getControlNodeList();
			totalSubCtrlNum = controlNodeList == null ? 0 : controlNodeList.Count;

			if (totalSubCtrlNum == 0)
			{
				string msg = "当前未检测到分控";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.2");
				}
				
				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				return;
			}

			if (mode.Equals("DownloadAddrMap"))
			{
				totalSubCtrlNum = baseCoreNet.getSubControlNumInLwf();
			}

			selectedSubInfo.withPreTreat = preTreatCheckBox.Checked;
			selectedSubInfo.overall = false;
			selectedSubInfo.enableManualOffset = false;
			selectedSubInfo.manualOffset = 0;

			// 所有分控
			if (allRadioButton.Checked)
			{
				int startIndex = 1;
				int endIndex = totalSubCtrlNumInLwf;

				selectedSubInfo.sourceSubIndexList.Clear();
				selectedSubInfo.targetSubIndexList.Clear();
				StringBuilder includeIndex = new StringBuilder();
				StringBuilder excludeIndex = new StringBuilder();
				for (int index = startIndex; index <= endIndex; index++)
				{
					bool findTarget = false;
					for (int k = 0; k < controlNodeList.Count; k++)
					{
						ControlNode node = controlNodeList[k];
						if (node.type == 1 && node.mySubCtrlDepth + 1 == index)
						{
							selectedSubInfo.sourceSubIndexList.Add(index);
							selectedSubInfo.targetSubIndexList.Add(node.mySubCtrlDepth + 1);
							includeIndex.Append(", " + index);
							findTarget = true;
							break;
						}
					}
					if (findTarget == false)
					{
						excludeIndex.Append(", " + index);
					}
				}

				if (!excludeIndex.ToString().Equals(""))
				{
					string s1 = string.Format("未检到的分控：{0}", excludeIndex.ToString().Substring(1));
					string s2 = "";
					if (includeIndex.ToString().Equals(""))
					{
						s2 = string.Format("可下载的分控：--");
					}
					else
					{
						s2 = string.Format("可下载的分控：{0}", includeIndex.ToString().Substring(1));
					}
					string s3 = "是否继续下载？";
					
					if (LanguageOper.available == true)
					{
						s1 = string.Format(LanguageOper.ReadValue(section, "msgStr.3"), excludeIndex.ToString().Substring(1));
						if (includeIndex.ToString().Equals(""))
						{
							s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), "--");
						}
						else
						{
							s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), includeIndex.ToString().Substring(1));
						}
						s3 = LanguageOper.ReadValue(section, "msgStr.5");
					}
					if (includeIndex.ToString().Equals(""))
					{
						string msg = "未检测到下载目标";
						if (LanguageOper.available == true)
						{
							msg = LanguageOper.ReadValue(section, "msgStr.24");
							MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
							return;
						}
					}
					else
					{
						string msg = s1 + "\n\n" + s2 + "\n\n" + s3;
						DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
						if (dr == System.Windows.Forms.DialogResult.No)
						{
							return;
						}
					}
				}
			}
			// 按序号指定分控
			else if (indexRadioButton.Checked)
			{
				int startIndex, endIndex;
				if (int.TryParse(indexStartTextBox.Text.Trim(), out startIndex) && int.TryParse(indexEndTextBox.Text.Trim(), out endIndex))
				{
					if (startIndex < 1 || startIndex > 255)
					{
						string msg = "起始分控编号应在 [1,255] 区间";
						if (LanguageOper.available == true)
						{
							msg = LanguageOper.ReadValue(section, "msgStr.6");
						}
						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}
					if (endIndex < 1 || endIndex > 255)
					{
						string msg = "结束分控编号应在 [1,255] 区间";
						if (LanguageOper.available == true)
						{
							msg = LanguageOper.ReadValue(section, "msgStr.7");
						}
						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}
					if (startIndex > endIndex)
					{
						string msg = "起始分控大于结束分控, 请重新指定";
						if (LanguageOper.available == true)
						{
							msg = LanguageOper.ReadValue(section, "msgStr.8");
						}
						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}

					/********************** 检查是否缺少数据源 *****************************/

					if (endIndex > totalSubCtrlNumInLwf)
					{
						StringBuilder notInLwfIndex = new StringBuilder();
						for (int i = totalSubCtrlNumInLwf + 1; i <= endIndex; i++)
						{
							notInLwfIndex.Append(", " + i);
						}
						
						string s1 = "下列分控的布线数据未在布线文件中：";
						string s2 = string.Format("分控{0}", notInLwfIndex.ToString().Substring(1));
						string s3 = "请重新指定分控序号";
						if (LanguageOper.available == true)
						{
							s1 = LanguageOper.ReadValue(section, "msgStr.9");
							s1 = string.Format(LanguageOper.ReadValue(section, "msgStr.10"), notInLwfIndex.ToString().Substring(1));
							s1 = LanguageOper.ReadValue(section, "msgStr.11");
						}
						string msg = s1 + "\n\n" + s2 + "\n\n" + s3;
						
						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						
						return;
					}

					/******************** End-检查是否缺少数据源 ***************************/

					// 启用端口起始分控号
					if (manualOffsetCheckBox.Enabled == true && manualOffsetCheckBox.Checked == true)
					{
						int manualOffset = -1;
						bool res = int.TryParse(manualOffsetTextBox.Text.Trim(), out manualOffset);
						if (res == false)
						{
							string msg = "端口起始分控号输入错误";
							if (LanguageOper.available == true)
							{
								msg = LanguageOper.ReadValue(section, "msgStr.12");
							}

							MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
							
							return;
						}
						else if (manualOffset < 1)
						{
							string msg = "端口起始分控号应为正整数";
							if (LanguageOper.available == true)
							{
								msg = LanguageOper.ReadValue(section, "msgStr.13");
							}

							MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
							
							return;
						}
						else if (manualOffset > startIndex)
						{
							string msg = "端口起始分控号设置错误";
							if (LanguageOper.available == true)
							{
								msg = LanguageOper.ReadValue(section, "msgStr.14");
							}

							MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
							
							return;
						}

						selectedSubInfo.enableManualOffset = true;
						selectedSubInfo.manualOffset = manualOffset;

						// 统计选中的分控
						selectedSubInfo.sourceSubIndexList.Clear();
						selectedSubInfo.targetSubIndexList.Clear();
						StringBuilder includeIndex = new StringBuilder();
						StringBuilder excludeIndex = new StringBuilder();
						for (int index = startIndex; index <= endIndex; index++)
						{
							int indexWithOffset = index - manualOffset + 1;
							bool findTarget = false;
							for (int k = 0; k < controlNodeList.Count; k++)
							{
								ControlNode node = controlNodeList[k];
								if (node.type == 1 && node.mySubCtrlDepth + 1 == indexWithOffset)
								{
									selectedSubInfo.sourceSubIndexList.Add(index);
									selectedSubInfo.targetSubIndexList.Add(node.mySubCtrlDepth + 1);
									includeIndex.Append(", " + indexWithOffset);
									findTarget = true;
									break;
								}
							}
							if (findTarget == false)
							{
								excludeIndex.Append(", " + indexWithOffset);
							}
						}

						if (!excludeIndex.ToString().Equals(""))
						{
							string s1 = string.Format("未检到的分控：{0}", excludeIndex.ToString().Substring(1));
							string s2 = "";
							if (includeIndex.ToString().Equals(""))
							{
								s2 = string.Format("可下载的分控：--");
							}
							else
							{
								s2 = string.Format("可下载的分控：{0}", includeIndex.ToString().Substring(1));
							}
							string s3 = "是否继续下载？";
							
							if (LanguageOper.available == true)
							{
								s1 = string.Format(LanguageOper.ReadValue(section, "msgStr.3"), excludeIndex.ToString().Substring(1));
								if (includeIndex.ToString().Equals(""))
								{
									s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), "--");
								}
								else
								{
									s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), includeIndex.ToString().Substring(1));
								}
								s3 = LanguageOper.ReadValue(section, "msgStr.5");
							}

							if (includeIndex.ToString().Equals(""))
							{
								string msg = "未检测到下载目标";
								if (LanguageOper.available == true)
								{
									msg = LanguageOper.ReadValue(section, "msgStr.24");
									MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
									return;
								}
							}
							else
							{
								string msg = s1 + "\n\n" + s2 + "\n\n" + s3;
								DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
								if (dr == System.Windows.Forms.DialogResult.No)
								{
									return;
								}
							}
						}
					}
					// 禁用端口起始分控号
					else
					{
						selectedSubInfo.sourceSubIndexList.Clear();
						selectedSubInfo.targetSubIndexList.Clear();
						StringBuilder includeIndex = new StringBuilder();
						StringBuilder excludeIndex = new StringBuilder();
						for (int index = startIndex; index <= endIndex; index++)
						{
							bool findTarget = false;
							for (int k = 0; k < controlNodeList.Count; k++)
							{
								ControlNode node = controlNodeList[k];
								if (node.type == 1 && node.mySubCtrlDepth + 1 == index)
								{
									selectedSubInfo.sourceSubIndexList.Add(index);
									selectedSubInfo.targetSubIndexList.Add(node.mySubCtrlDepth + 1);
									includeIndex.Append(", " + index);
									findTarget = true;
									break;
								}
							}
							if (findTarget == false)
							{
								excludeIndex.Append(", " + index);
							}
						}

						if (!excludeIndex.ToString().Equals(""))
						{
							string s1 = string.Format("未检到的分控：{0}", excludeIndex.ToString().Substring(1));
							string s2 = "";
							if (includeIndex.ToString().Equals(""))
							{
								s2 = string.Format("可下载的分控：--");
							}
							else
							{
								s2 = string.Format("可下载的分控：{0}", includeIndex.ToString().Substring(1));
							}
							string s3 = "是否继续下载？";
							
							if (LanguageOper.available == true)
							{
								s1 = string.Format(LanguageOper.ReadValue(section, "msgStr.3"), excludeIndex.ToString().Substring(1));
								if (includeIndex.ToString().Equals(""))
								{
									s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), "--");
								}
								else
								{
									s2 = string.Format(LanguageOper.ReadValue(section, "msgStr.4"), includeIndex.ToString().Substring(1));
								}
								s3 = LanguageOper.ReadValue(section, "msgStr.5");
							}

							if (includeIndex.ToString().Equals(""))
							{
								string msg = "未检测到下载目标";
								if (LanguageOper.available == true)
								{
									msg = LanguageOper.ReadValue(section, "msgStr.24");
									MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
									return;
								}
							}
							else
							{
								string msg = s1 + "\n\n" + s2 + "\n\n" + s3;
								DialogResult dr = MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
								if (dr == System.Windows.Forms.DialogResult.No)
								{
									return;
								}
							}
						}
					}
				}
				else
				{
					string msg = "分控编号输入错误";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.15");
					}

					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					
					return;
				}
			}

			// 启用 "使用布线配置表调整布线数据"
			if (useTableCheckBox.Checked)
			{
				// 检查表格数据
				string checkResult = checkLwfConfigData();

				if (checkResult.Equals("hasEmptyValue") || checkResult.Equals("hasErrorValue"))
				{
					return;
				}
				else if (!checkResult.Equals(""))
				{
					MessageBoxEx.Show(this, checkResult, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					return;
				}

				// 检查通过, 收集信息
				selectedSubInfo.useAddrMapOffsetTable = true;
				selectedSubInfo.addrMapOffsetList = new List<AddrMapOffset>();
				for (int i = 0; i < configDataGridView.Rows.Count - 1; i++)
				{
					AddrMapOffset addrMapOffset = new AddrMapOffset();
					addrMapOffset.startIndex = int.Parse(configDataGridView.Rows[i].Cells[0].Value.ToString());
					addrMapOffset.endIndex = int.Parse(configDataGridView.Rows[i].Cells[1].Value.ToString());
					addrMapOffset.offsetX = int.Parse(configDataGridView.Rows[i].Cells[2].Value.ToString());
					addrMapOffset.offsetY = int.Parse(configDataGridView.Rows[i].Cells[3].Value.ToString());
					selectedSubInfo.addrMapOffsetList.Add(addrMapOffset);
				}
			}

			// for debug
			//StringBuilder downloadPair = new StringBuilder();
			//for (int i = 0; i < selectedSubInfo.sourceSubIndexList.Count; i++)
			//{
			//	downloadPair.Append("\n" + selectedSubInfo.sourceSubIndexList[i] + " -> " + selectedSubInfo.targetSubIndexList[i]);
			//}
			//MessageBoxEx.Show(this, "下载信息核对：\n" + downloadPair.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
			//return;

			this.DialogResult = DialogResult.OK;
		}

		// 取消
		private void cancelButton_Click(object sender, EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
		}

		// 使用布线配置表调整布线数据
		private void useTableCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			configGroupBox.Enabled = useTableCheckBox.Checked;

			if (!useTableCheckBox.Checked)
			{
				unSelectAllCells();
			}
		}

		// 菜单创建基本函数
		private ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
		{
			if (text == "-")
			{
				ToolStripSeparator tsp = new ToolStripSeparator();
				cms.Add(tsp);
				return null;
			}
			else if (!string.IsNullOrEmpty(text))
			{
				ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
				if (callback != null)
				{
					tsmi.Click += callback;
				}
				cms.Add(tsmi);
				return tsmi;
			}

			return null;
		}

		// 布线配置文件 - 菜单按钮
		private void configButton_Click(object sender, EventArgs e)
		{
			// 设置 menu 显示位置
			Point pt = new Point(configButton.Location.X, configButton.Location.Y + configButton.Height);
			this.configContextMenuStrip.Show(this.configGroupBox, pt);
			this.BringToFront();
		}

		// 布线配置文件 - 新建
		private void newLwfConfigFile_Click(object sender, EventArgs e)
		{
			configDataGridView.Rows.Clear();
			configTableTextBox.Text = "";
		}

		// 布线配置文件 - 打开
		private void openLwfConfigFile_Click(object sender, EventArgs e)
		{
			OpenFileDialog o = new OpenFileDialog();
			o.Filter = "Json Files(*.json)|*.json";
			o.Multiselect = false;
			if (Directory.Exists(parent_parent.lastPath_SelectSubEx_LwfConfigFile))
			{
				o.InitialDirectory = parent_parent.lastPath_SelectSubEx_LwfConfigFile;
			}
			else
			{
				o.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
			}
			if (o.ShowDialog() == DialogResult.OK)
			{
				StreamReader reader = null;
				try
				{
					reader = new StreamReader(o.FileName);
					StringBuilder sb = new StringBuilder();
					string line = null;
					while (true)
					{
						line = reader.ReadLine();
						if (line == null)
						{
							break;
						}
						else
						{
							sb.Append(line);
						}
					}
					string jsonStr = sb.ToString();
					List<AddrMapOffset> addrMapOffsetList = JsonConvert.DeserializeObject<List<AddrMapOffset>>(jsonStr);
					if(addrMapOffsetList != null)
					{
						configDataGridView.Rows.Clear();
						foreach(AddrMapOffset addrMapOffset in addrMapOffsetList)
						{
							configDataGridView.Rows.Add(addrMapOffset.startIndex, addrMapOffset.endIndex, addrMapOffset.offsetX, addrMapOffset.offsetY);
						}
						unSelectAllCells();
						checkLwfConfigData();

						configTableTextBox.Text = o.FileName;
						configTableTextBox.SelectionStart = configTableTextBox.Text.Length;
						configTableTextBox.ScrollToCaret();
					}
					else
					{
						string msg = string.Format("布线配置文件 {0} 数据内容错误", o.FileName);
						if (LanguageOper.available == true)
						{
							msg = string.Format(LanguageOper.ReadValue(section, "msgStr.16"), o.FileName);
						}

						MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
						
						return;
					}

					parent_parent.lastPath_SelectSubEx_LwfConfigFile = (new FileInfo(o.FileName)).DirectoryName;
				}
				catch (Exception)
				{
					string msg = string.Format("布线配置文件 {0} 数据内容错误", o.FileName);
					if (LanguageOper.available == true)
					{
						msg = string.Format(LanguageOper.ReadValue(section, "msgStr.16"), o.FileName);
					}

					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
					
					return;
				}
				finally
				{
					if(reader != null)
					{
						reader.Close();
					}
				}
			}
		}

		// 布线配置文件 - 保存
		private void saveLwfConfigFile_Click(object sender, EventArgs e)
		{
			// 检查表格数据
			string checkResult = checkLwfConfigData();
			
			if (checkResult.Equals("hasEmptyValue"))
			{
				string msg = "布线配置表填写不完整";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.17");
				}

				MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				
				return;
			}
			else if (!checkResult.Equals(""))
			{
				MessageBoxEx.Show(this, checkResult, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				return;
			}

			// 检查通过, 收集信息
			List<AddrMapOffset> addrMapOffsetList = new List<AddrMapOffset>();
			for (int i = 0; i < configDataGridView.Rows.Count - 1; i++)
			{
				AddrMapOffset addrMapOffset = new AddrMapOffset();
				addrMapOffset.startIndex = int.Parse(configDataGridView.Rows[i].Cells[0].Value.ToString());
				addrMapOffset.endIndex = int.Parse(configDataGridView.Rows[i].Cells[1].Value.ToString());
				addrMapOffset.offsetX = int.Parse(configDataGridView.Rows[i].Cells[2].Value.ToString());
				addrMapOffset.offsetY = int.Parse(configDataGridView.Rows[i].Cells[3].Value.ToString());
				addrMapOffsetList.Add(addrMapOffset);
			}

			SaveFileDialog s = new SaveFileDialog();
			s.Filter = "Json Files(*.json)|*.json";
			s.FilterIndex = 1;
			s.FileName = configTableTextBox.Text;
			if (s.ShowDialog() == DialogResult.OK)
			{
				try
				{
					string jsonStr = JsonConvert.SerializeObject(addrMapOffsetList);
					StreamWriter writer = new StreamWriter(s.FileName);
					writer.WriteLine(jsonStr);
					writer.Flush();
					writer.Close();

					configTableTextBox.Text = s.FileName;
					configTableTextBox.SelectionStart = configTableTextBox.Text.Length;
					configTableTextBox.ScrollToCaret();

					string msg = "布线配置表保存成功";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.18");
					}

					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
				catch(Exception)
				{
					string msg = "布线配置表保存失败";
					if (LanguageOper.available == true)
					{
						msg = LanguageOper.ReadValue(section, "msgStr.19");
					}

					MessageBoxEx.Show(this, msg, tip, MessageBoxButtons.OK, MessageBoxIcon.Information);
				}
			}
		}

		// 布线配置文件 - 检查表格数据
		private string checkLwfConfigData()
		{
			int rowCount = configDataGridView.Rows.Count;
			
			// 检查有效数据行
			if (rowCount == 1)
			{
				string msg = "布线配置表中没有有效的数据行";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.20");
				}

				return msg;
			}

			// 检查空值
			bool hasEmptyValue = false;
			for (int i = 0; i < rowCount - 1; i++)
			{
				for (int k = 0; k < 4; k++)
				{
					configDataGridView.Rows[i].Cells[k].Selected = false;
					if (configDataGridView.Rows[i].Cells[k].Value == null || configDataGridView.Rows[i].Cells[k].Value.ToString().Trim().Equals(""))
					{
						configDataGridView.Rows[i].Cells[k].Style.BackColor = Color.Red;
						hasEmptyValue = true;
					}
					else
					{
						configDataGridView.Rows[i].Cells[k].Style.BackColor = Color.White;
					}
				}
			}
			if (hasEmptyValue == true)
			{
				return "hasEmptyValue";
			}
				
			// 检查分控编号、偏移量范围
			bool hasErrorValue = false;
			for (int i = 0; i < rowCount - 1; i++)
			{
				int start = int.Parse(configDataGridView.Rows[i].Cells[0].Value.ToString().Trim());
				int end = int.Parse(configDataGridView.Rows[i].Cells[1].Value.ToString().Trim());
				configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.White;
				configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.White;
				if (start < 0)
				{
					configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Red;
					hasErrorValue = true;
				}
				if (end < 0)
				{
					configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.Red;
					hasErrorValue = true;
				}
			}
			if (hasErrorValue == true)
			{
				return "hasErrorValue";
			}

			// 检查结束 >= 起始
			bool hasWrongStartEnd = false;
			for (int i = 0; i < rowCount - 1; i++)
			{
				int start = int.Parse(configDataGridView.Rows[i].Cells[0].Value.ToString().Trim());
				int end = int.Parse(configDataGridView.Rows[i].Cells[1].Value.ToString().Trim());
				if (end < start)
				{
					configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Orange;
					configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.Orange;
					hasWrongStartEnd = true;
				}
				else
				{
					configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.White;
					configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.White;
				}
			}
			if (hasWrongStartEnd == true)
			{
				string msg = "结束分控号应不小于起始分控号";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.21");
				}

				return msg;
			}

			// 检查重复区间
			bool hasRepeat = false;
			for (int i = 0; i < rowCount - 1; i++)
			{
				int checkStart = int.Parse(configDataGridView.Rows[i].Cells[0].Value.ToString().Trim());
				int checkEnd = int.Parse(configDataGridView.Rows[i].Cells[1].Value.ToString().Trim());
				for (int k = 0; k < i; k++)
				{
					int start = int.Parse(configDataGridView.Rows[k].Cells[0].Value.ToString().Trim());
					int end = int.Parse(configDataGridView.Rows[k].Cells[1].Value.ToString().Trim());
					if ((checkStart <= end && checkEnd >= start)|| (checkEnd >= start && checkStart <= end))
					{
						hasRepeat = true;
						configDataGridView.Rows[i].Cells[0].Style.BackColor = Color.Orange;
						configDataGridView.Rows[i].Cells[1].Style.BackColor = Color.Orange;
						configDataGridView.Rows[k].Cells[0].Style.BackColor = Color.Orange;
						configDataGridView.Rows[k].Cells[1].Style.BackColor = Color.Orange;
						break;
					}
				}
			}
			if (hasRepeat)
			{
				string msg = "布线配置表存在重复区间, 请检查";
				if (LanguageOper.available == true)
				{
					msg = LanguageOper.ReadValue(section, "msgStr.22");
				}

				return msg;
			}

			//return "检查通过";
			return "";
		}

		#region 界面控件

		// 删除当前行
		private void configDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (configDataGridView.CurrentCell.ColumnIndex != 4)
			{
				return;
			}

			if (configDataGridView.CurrentCell.Value == null)
			{
				return;
			}

			configDataGridView.Rows.RemoveAt(configDataGridView.CurrentCell.RowIndex);
		}

		// 添加行时, 设置删除按钮文字
		private void configDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
		{
			string delStr = "";
			if (LanguageOper.available == true)
			{
				delStr = LanguageOper.ReadValue(section, "str.0");
			}

			for (int i = 0; i < configDataGridView.RowCount - 1; i++)
			{
				configDataGridView.Rows[i].Cells[4].Value = delStr;
			}
		}

		// 有控件处于编辑状态
		private void configDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
		{
			editingControl = (DataGridViewTextBoxEditingControl)e.Control;

			editingControl.TextChanged += new EventHandler(editingControl_TextChanged);

			lastEffectEditString = editingControl.Text;
		}

		// 编辑态控件的文字默认为数字
		private void editingControl_TextChanged(object sender, EventArgs e)
		{
			if (initDone == false)
			{
				return;
			}

			if (editFormatAction == false)
			{
				return;
			}

			string value = editingControl.Text;

			int intValue = 0;
			bool res = int.TryParse(value.Trim(), out intValue);

			if (res == true || value.Trim().Equals(""))
			{
				editFormatAction = false;
				editingControl.Text = value.Trim();
				lastEffectEditString = value.Trim();
				editFormatAction = true;
			}
			else
			{
				editFormatAction = false;
				editingControl.Text = lastEffectEditString;
				editFormatAction = true;
			}
			editingControl.SelectionStart = editingControl.Text.Length;
			editingControl.ScrollToCaret();
		}

		// 取消所有选定的单元格
		private void unSelectAllCells()
		{
			for (int i = 0; i < configDataGridView.Rows.Count; i++)
			{
				for (int k = 0; k < 4; k++)
				{
					configDataGridView.Rows[i].Cells[k].Selected = false;
				}
			}
		}

		// 布线配置表不再为活动控件
		private void configDataGridView_Leave(object sender, EventArgs e)
		{
			unSelectAllCells();
		}

		#endregion

		private void manualOffsetCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			manualOffsetTextBox.Enabled = manualOffsetCheckBox.Checked;
		}

	}
}
